package sg.com.techstudio.tafep.email;

import java.io.File;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class GenericHTMLPreparator implements MimeMessagePreparator{
	public static final String EMAIL_SEPARATOR = ",;";
	private VelocityEngine velocityEngine;
	private Map<String, Object> model;
	private String from, senderName, to, subject, templateLocation, bcc, cc;
	private File attachFile;

	public File getAttachFile() {
		return attachFile;
	}

	public String getBcc() {
		return bcc;
	}

	public void setBcc(String bcc) {
		this.bcc = bcc;
	}

	public String getCc() {
		return cc;
	}

	public void setCc(String cc) {
		this.cc = cc;
	}

	public void setAttachFile(File attachFile) {
		this.attachFile = attachFile;
	}

	public String getSenderName() {
		return senderName;
	}

	public void setSenderName(String senderName) {
		this.senderName = senderName;
	}

	public String getTemplateLocation() {
		return templateLocation;
	}

	public void setTemplateLocation(String templateLocation) {
		this.templateLocation = templateLocation;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public Map<String, Object> getModel() {
		return model;
	}

	public void setModel(Map<String, Object> model) {
		this.model = model;
	}

	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	@Override
	public void prepare(MimeMessage mimeMessage) throws Exception {
		MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
		message.setTo(StringUtils.split(to, EMAIL_SEPARATOR));
		if(!StringUtils.isBlank(cc))
			message.setCc(cc);
		if(!StringUtils.isBlank(bcc))
			message.setBcc(bcc);
		message.setFrom(from, senderName);
		message.setSubject(subject);
		message.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, "UTF-8", model), true);
		if(attachFile!=null && attachFile.exists())
			message.addAttachment(attachFile.getName(), attachFile);
	}

}
